package org.sraosha.microservice.oauth2.service.impl;

import org.sraosha.microservice.oauth2.model.User;
import org.sraosha.microservice.oauth2.pojo.UserInfo;
import org.sraosha.microservice.oauth2.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * UserInfoService接口的实现类
 */
@Slf4j
@Service
@Transactional
public class UserInfoServiceImpl implements UserInfoService {

    @Resource
    private ServiceHelper serviceHelper;

    /**
     * 根据username，查找UserInfo对象
     *
     * @param username
     * @return
     */
    @Override
    public UserInfo findByUsername(String username) {
        User user = serviceHelper.getUserMapper().findUserByUserName(username);
        List<GrantedAuthority>  grantedAuthorityList = new ArrayList<>();
        if (null != user) {
            List<String> roleList = serviceHelper.getMapUserRoleMapper().findRoleNameListByUsername(username);
            if (null != roleList && roleList.size() > 0) {
                for (int i=0; i<roleList.size(); i++){
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(roleList.get(i));
                    grantedAuthorityList.add(grantedAuthority);
                }
            }
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(user.getUsername());
        userInfo.setId(user.getId());
        userInfo.setAuthorities(grantedAuthorityList);
        return userInfo;
    }
}
